package com.joney.mq.activemq;

import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Queue;

import com.joney.mq.pojo.Content;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wangxianchen
 * @create 2018-03-06
 * @desc
 */
@Service("producer")
@EnableScheduling
public class Producer implements CommandLineRunner { //

    @Autowired
    private JmsMessagingTemplate jmsTemplate; // 也可以注入JmsTemplate，JmsMessagingTemplate对JmsTemplate进行了封装

    //@Autowired
   // private Queue queue;

    // 发送消息，destination是发送到的队列，message是待发送的消息
    public void send(Destination destination, final String message){
        jmsTemplate.convertAndSend(destination, message);
    }

    public void send(Destination destination, final Content content){

        jmsTemplate.convertAndSend(destination, content);
    }

    /**
     * @desc implements CommandLineRunner 应用启动后会执行一次
     * @author wangxianchen
     * @create 2018-03-06
     * @param strings
     * @throws Exception
     */
    @Override
    public void run(String... strings) throws Exception {

    }

    @Scheduled(fixedDelay=2000)//每2s执行1次
    public void send() {
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //Destination destDirect = new ActiveMQQueue("direct.queue"); //创建点对点模式
       // jmsTemplate.convertAndSend(destDirect, "direct--> "+now);

        Destination destTopic = new ActiveMQTopic("topic.queue");  //发布订阅模式
        jmsTemplate.convertAndSend(destTopic, "topic--> "+now);
    }
}